package cn.tjad.tjad2.module.user.userselect;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baozi.treerecyclerview.adpater.TreeRecyclerAdapter;
import com.baozi.treerecyclerview.adpater.TreeRecyclerType;
import com.baozi.treerecyclerview.factory.ItemHelperFactory;
import com.baozi.treerecyclerview.item.TreeItem;
import com.qiandian.android.base.activity.BaseActivity;
import com.qiandian.android.base.common.bean.CommonListBean;
import com.qiandian.android.base.net.http.HttpConstants;
import com.qiandian.android.base.net.http.HttpId;
import com.qiandian.android.base.net.http.IDataCallBack;
import com.qiandian.android.base.widget.TJADTTitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.business.RemoteDataService;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.Department;
import cn.tjad.tjad2.data.bean.Member;
import cn.tjad.tjad2.data.bean.User;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.Tools;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

@Route(path = PageId.USER_SELECT_2)
public class UserSelectActivity2 extends BaseActivity implements IDataCallBack, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    private TreeRecyclerAdapter treeRecyclerAdapter;
    private List<Member> memberList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_recylerview);
        if (SelectMode.getSelectMode() == SelectMode.SINGGLE_CHOICE) {
            EventBus.getDefault().register(this);
        }
        swipeRefreshLayout.setOnRefreshListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        treeRecyclerAdapter = new TreeRecyclerAdapter(TreeRecyclerType.SHOW_EXPAND);
        recyclerView.setAdapter(treeRecyclerAdapter);
        requestCompany();
    }

    @Override
    protected void setCustomerTitle(TJADTTitleView titleView) {
        super.setCustomerTitle(titleView);
        titleView.setRightText("确认");
        titleView.showRight(true);
    }

    @Override
    public void onTitleClick(int which) {
        super.onTitleClick(which);
        switch (which) {
            case TJADTTitleView.TITLE_RIGHT:
                onConfirmUserSelect();
                break;
        }
    }

    private void onConfirmUserSelect() {
        ArrayList<User> selectedUser = new ArrayList<>();
        if (memberList != null && memberList.size() > 0) {
            Observable.fromIterable(memberList)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .filter(member -> member.departmentList != null && member.departmentList.size() > 0)
                    .flatMap((Function<Member, ObservableSource<Department>>) member -> Observable.fromIterable(member.departmentList))
                    .filter(department -> department.userList != null && department.userList.size() > 0)
                    .flatMap((Function<Department, ObservableSource<User>>) department -> Observable.fromIterable(department.userList))
                    .filter(user -> user.isChecked)
                    .doOnNext(user -> {
                        selectedUser.add(user);
                    }).subscribe(new Observer<User>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(User user) {

                }

                @Override
                public void onError(Throwable e) {
                    Log.d("userSelect", "", e);
                }

                @Override
                public void onComplete() {
                    if (selectedUser.size() > 0) {
                        Intent intent = new Intent();
                        intent.putExtra(Keys.SELECTED_RESULTS, selectedUser);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                }
            });
        }

    }

    private void requestCompany() {
        RemoteDataService.getMemberList(Tools.getProjectId(), this);
    }


    @Override
    public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
        if (httpId == HttpId.MEMBER_LIST) {
            if (!TextUtils.isEmpty(errorMsg)) {
                Tools.showToast(errorMsg);
            } else {
                Tools.showToast("获取成员列表失败!");
            }
            swipeRefreshLayout.setRefreshing(false);
        }
        return false;
    }

    @Override
    public void onDataRefresh(int httpId, Object responseBean) {
        if (httpId == HttpId.MEMBER_LIST) {
            CommonListBean<Member> bean = (CommonListBean<Member>) responseBean;
            if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                onMemberListGet(bean.result);
            } else {
                Tools.showToast(bean.respMsg);
            }
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    private void onMemberListGet(ArrayList<Member> result) {
        memberList = result;
        List<TreeItem> items = ItemHelperFactory.createTreeItemList(result, CompanyItemParent.class, null);
//        List<TreeItem> items = ItemHelperFactory.createItems(result, null);
        treeRecyclerAdapter.getItemManager().replaceAllItem(items);
    }

    @Override
    public void onRefresh() {
        requestCompany();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (SelectMode.getSelectMode() == SelectMode.SINGGLE_CHOICE) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe
    public void onUserCheckedEvent(UserCheckedEvent event) {
        if (memberList != null && memberList.size() > 0) {
            for (Member member: memberList) {
                if (member.departmentList != null && member.departmentList.size() > 0) {
                    for (Department department: member.departmentList) {
                        if (department.userList != null && department.userList.size() > 0) {
                            for (User user: department.userList) {
                                if (event.getCheckedUser() != user) {
                                    user.isChecked = false;
                                }
                            }
                        }
                    }
                }
            }
            treeRecyclerAdapter.notifyDataSetChanged();
        }
    }
}
